const Mock = require('mockjs')
const { find: findOrgUnit, list: listOrgUnits } = require('./org-units')
const { find: findMovieLevel } = require('./movie-level')
const { getLoginUser } = require('./login')

let CouponDefs = []
const orgUnitsPage = listOrgUnits(1, 10)
let id = 1
for (let i = 0; i < orgUnitsPage.data.records.length; ++i) {
  for (let j = 1; j <= 3; ++j) {
    CouponDefs.push(Mock.mock({
      id: id++,
      name: '折扣券' + j,
      type: 1,
      amount: j * 20,
      orgUnitId: orgUnitsPage.data.records[i].id,
      movieLevelId: j === 1 ? 1 : j === 2 ? 2 : -1,
      maxAmount: j === 1 ? 6000 : j === 2 ? 5000 : -1
    }))
    CouponDefs.push(Mock.mock({
      id: id++,
      name: '金额券' + j,
      type: 2,
      amount: j * 8000,
      orgUnitId: orgUnitsPage.data.records[i].id,
      movieLevelId: j === 1 ? 1 : j === 2 ? 2 : -1,
      maxAmount: -1
    }))
  }
}

function add(item) {
  const r = JSON.parse(JSON.stringify(item))
  const u = getLoginUser()
  console.log('loginUser=' + JSON.stringify(u))
  r.orgUnitId = u.orgUnitId
  r.id = CouponDefs[CouponDefs.length - 1].id + 1
  CouponDefs.push(r)
}

function list(page, limit, name, orgUnitId, type) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  type = type ? parseInt(type) : null
  let mocks = CouponDefs.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (type && item.type !== type) return false
    return !(name && (!item.name || item.name.indexOf(name) === -1))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  mocks = mocks.map(d => {
    const o = findOrgUnit(d.orgUnitId)
    const r = findMovieLevel(d.movieLevelId)
    return { ...d, orgUnitName: o ? o.name : '', movieLevelName: r ? r.name : d.movieLevelId === -1 ? '无限制' : '未知' }
  })
  return { success: true, data: { total: total, records: mocks }}
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < CouponDefs.length; ++i) {
    if (CouponDefs[i].id === id) {
      return CouponDefs[i]
    }
  }
  return null
}

function deleteRecord(id) {
  id = id ? parseInt(id) : null
  if (id) {
    CouponDefs = CouponDefs.filter(item => item.id !== id)
  }
}

module.exports = { list, add, find, deleteRecord }
